#!/bin/bash

BINDIR=$(cd $(dirname $0) && pwd)

. ${BINDIR}/common
. ${BINDIR}/functions

if [ "x$1" = "x" ]
then
	echo "USAGE: $0 BRANCHNAME"
	exit 1
fi

teeOutput

echo "$0 running to switch branches to $1"

CNT=`cd ${FPPDIR} && git show-ref | grep "refs/remotes/origin" | grep -i $1 | wc -l`
if [ $CNT -eq 0 ]; then
	echo "Invalid Branch Name: $1"
	exit 1
fi

echo "Stopping fppd"
${SUDO} ${FPPDIR}/scripts/fppd_stop

echo "Cleaning up any compiled binaries"
cleanCompiledBinaries

echo "Switching git branch to $1"
if [ "x${FPPDIR}" = "x/opt/fpp" ]
then
	cd ${FPPDIR} && $SUDO git clean -df && $SUDO git reset --hard && $SUDO git checkout $1 && $SUDO git pull && git fetch --tags -f && $SUDO git submodule sync && $SUDO git submodule update --init
else
	cd ${FPPDIR} && sudo git clean -df && sudo -u ${FPPUSER} git reset --hard && sudo -u ${FPPUSER} git checkout $1 && sudo -u ${FPPUSER} git pull && sudo -u ${FPPUSER} git submodule sync && sudo git submodule update --init
fi

${SUDO} ${SCRIPTDIR}/upgrade_config

echo "Compiling Binaries"
compileBinaries

echo "Restarting fppd"
${SUDO} ${FPPDIR}/scripts/fppd_start

